package com.qianyitian.hope2.spider.fetcher;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qianyitian.hope2.spider.config.PropertyConfig;
import com.qianyitian.hope2.spider.external.XiaoXiongClient;
import com.qianyitian.hope2.spider.model.KLineInfo;
import com.qianyitian.hope2.spider.model.Stock;
import com.qianyitian.hope2.spider.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


@Component("xiaoxiongFundRetreiver")
public class XiaoxiongFundRetreiver extends WebStockRetreiver {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    PropertyConfig propertyConfig;
    @Autowired
    private XiaoXiongClient xiaoXiongClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Stock fetchStockInfo(Stock stock) throws IOException {
        return fetchIndexInfo(stock);
    }

    @Override
    public String fetchFundsInfo(String code) throws IOException {
        String content = xiaoXiongClient.getFundDetail(code, propertyConfig.getXiaoxiongToken());
        return content;
    }

    @Override
    public Stock fetchIndexInfo(Stock stock) throws IOException {
        String content = xiaoXiongClient.getIndexKlineDay(stock.getCode(), propertyConfig.getXiaoxiongToken());
        JSONObject jsonObject = JSON.parseObject(content);

        String resCode = jsonObject.getString("code");
        if (!"200".equals(resCode)) {
            logger.error(jsonObject.toJSONString());
            return null;
        }


        List<KLineInfo> kLineInfos = new LinkedList<KLineInfo>();

        JSONArray array = jsonObject.getJSONArray("data");
        int size = array.size();

        Double circulationVolume = 1.0;

        String info = (String) redisTemplate.opsForHash().get("stockProfiles", stock.getCode());
        if (info == null) {
            circulationVolume = 1.0;
        } else {
            JSONObject stockJson = JSON.parseObject(info);
            Double v = stockJson.getDouble("circulationVolume");
            if (v != null) {
                circulationVolume = v;
            }
        }

        for (int i = 0; i < size; i++) {
            KLineInfo daily = new KLineInfo();
            JSONArray bar = array.getJSONArray(i);
            LocalDate date = Utils.parseDate(bar.getString(0));
            double open = bar.getDouble(1);
            double close = bar.getDouble(2);
            double high = bar.getDouble(3);
            double low = bar.getDouble(4);
            double turnoverRate = bar.getDouble(5);
            turnoverRate = turnoverRate * 100 * 100 / circulationVolume;

            daily.setOpen(open);
            daily.setHigh(high);
            daily.setLow(low);
            daily.setClose(close);
            daily.setDate(date);
            daily.setTurnoverRate(turnoverRate);
            if (i > 0) {
                JSONArray yesterday = array.getJSONArray(i - 1);
                double change = Utils.calcRange(yesterday.getDouble(2), close) * 100;
                daily.setChangePercent(change);
            }
            kLineInfos.add(daily);
        }
        stock.setkLineInfos(kLineInfos);
        stock.setkLineType(Stock.TYPE_DAILY);
        return stock;
    }

    public String fetchStockProfile(Stock stock) throws IOException {
        String content = xiaoXiongClient.getStockProfile(stock.getCode(), propertyConfig.getXiaoxiongToken());
        JSONObject jsonObject = JSON.parseObject(content);
        List<KLineInfo> kLineInfos = new LinkedList<KLineInfo>();

        JSONArray array = jsonObject.getJSONArray("data");
        if (array.isEmpty()) {
            return null;
        } else {
            JSONObject json = array.getJSONObject(0);
            String name = json.getString("name");
            double circulationWorth = json.getDouble("circulationWorth");
            double close = json.getDouble("close");
            double volume = json.getDouble("volume");
            //流通股本
            double circulationVolume = (circulationWorth * 100000000) / close;

            Double pe = json.getDouble("pe");
            if (pe == null) {
                pe = 0.0;
            }
            Double spe = json.getDouble("spe");
            if (spe == null) {
                spe = 0.0;
            }
            String date = json.getString("date");

            Map map = new HashMap();
            map.put("name", name);
            map.put("circulationWorth", circulationWorth);
            map.put("circulationVolume", circulationVolume);
            map.put("pe", pe);
            map.put("spe", spe);
            map.put("date", date);
            return JSON.toJSONString(map);
        }

    }
}
